package com.qk.manangement.runner;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.properties.RedisExpTimeProperties;
import com.qk.common.properties.RedisProperties;
import com.qk.common.response.OverviewBussinessVO;
import com.qk.common.response.OverviewClueVO;
import com.qk.common.response.OverviewVO;
import com.qk.manangement.mapper.BusinessMapper;
import com.qk.manangement.mapper.ClueMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
@Slf4j
public class CachePreloadRunner implements ApplicationRunner {
    
    @Autowired
    private BusinessMapper businessMapper;
    
    @Autowired
    private ClueMapper clueMapper;
    
    @Autowired
    private StringRedisTemplate redisClient;
    
    @Autowired
    private RedisExpTimeProperties redisConfigProperties;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        preloadOverviewData();
    }
    
    private void preloadOverviewData() {
        try {
            String key = RedisProperties.REDIS_KEY_PREFIX + RedisProperties.REDIS_KEY_OVERVIEW;
            
            // 从数据库加载数据
            OverviewBussinessVO businessVO = businessMapper.getOvewInfor();
            OverviewClueVO clueVO = clueMapper.getOverviewInfor();
            
            OverviewVO overviewVO = BeanUtil.copyProperties(businessVO, OverviewVO.class);
            BeanUtil.copyProperties(clueVO, overviewVO);
            
            // 写入Redis缓存
            String jsonStr = JSONUtil.toJsonStr(overviewVO);
            redisClient.opsForValue().set(
                key, 
                jsonStr, 
                Duration.ofSeconds(redisConfigProperties.getOverviewExpireTime())
            );
            
            log.info("应用启动时Redis缓存预热完成");
        } catch (Exception e) {
            log.error("应用启动时Redis缓存预热失败: {}", e.getMessage(), e);
        }
    }
}
